﻿@page "/PublishServices"
@using Renci.SshNet
@using Tool.Models
@using Tool.Utils
@inject ISnackbar snackbar;
@implements IDisposable
<PageTitle>Publish Service</PageTitle>
<MudText Typo="Typo.h3" GutterBottom="true">命泉</MudText>
<MudGrid>
    <MudItem xs="3">
        <MudSelect @bind-Value="_server" Label="选择服务器" Variant="Variant.Text" Clearable Adornment="Adornment.Start" AdornmentIcon="@Icons.Material.Filled.LocationOn">
            @foreach (var site in _servers)
            {
                <MudSelectItem Value="@site.SiteUrl">@site.Name</MudSelectItem>
            }
        </MudSelect>
    </MudItem>
    <MudItem xs="6">
        <MudTextField @bind-Value="_commandText" Label="执行命令" Variant="Variant.Text" Adornment="Adornment.Start"
                      AdornmentIcon="@Icons.Material.Filled.LockPerson" Clearable="true" OnKeyUp="(KeyboardEventArgs eventArgs) => Process(eventArgs)" />
    </MudItem>

    <MudItem xs="3" Class="align-content-center">
        <MudButton Class="align-self-center" FullWidth="true" Disabled="@_processing" OnClick="(MouseEventArgs eventArgs) => Process(null)" Variant="Variant.Filled" Color="Color.Primary">
            @if (_processing)
            {
                <MudProgressCircular Class="ms-n1" Indeterminate="true" />
                <MudText Class="ms-2">Processing</MudText>
            }
            else
            {
                <MudText>执行</MudText>
            }
        </MudButton>
    </MudItem>


    <MudItem xs="6">
        <MudCard>
            <MudCardContent>
                <MudText>历史命令</MudText>
                @foreach (var result in _historyCommandTexts)
                {
                    <MudText Typo="Typo.body2">@result</MudText>
                }

            </MudCardContent>
            <MudCardActions>
                <MudButton Variant="Variant.Text" Color="Color.Primary" OnClick="ClearHistories">清除历史</MudButton>
            </MudCardActions>
        </MudCard>
    </MudItem>
    <MudItem xs="6">
        <MudCard>
            <MudCardContent>
                <MudText>执行结果</MudText>
                @foreach (var result in _results)
                {
                    <MudText Typo="Typo.body2">@result</MudText>
                }

            </MudCardContent>
            <MudCardActions>
                <MudButton Variant="Variant.Text" Color="Color.Primary" OnClick="ClearResult">清除结果</MudButton>
            </MudCardActions>
        </MudCard>
    </MudItem>
</MudGrid>


@code {
    private string _server = "192.198.0.202";
    private string _commandText = string.Empty;
    private List<string> _historyCommandTexts = new List<string>();
    private List<string> _results = new List<string>();
    private List<SiteInfo> _servers = new()
    {
        new SiteInfo { Name = "太极202", SiteUrl = "192.198.0.202" },
        new SiteInfo { Name = "太极3)", SiteUrl = "192.164.18.3" },
        // new SiteInfo { Name = "北京", SiteUrl = "192.198.0.90" },
        // new SiteInfo { Name = "云南", SiteUrl = "192.198.0.70" },
        // new SiteInfo { Name = "云南内网", SiteUrl = "192.198.0.62" }
    };

    private bool _processing = false;

    private SshConnectionPool sshConnectionPool;
    // private ImprovedJumpHostConnectionManager connectionManager = new ImprovedJumpHostConnectionManager();

    public void Dispose()
    {
        sshConnectionPool?.Dispose();
        // connectionManager?.Dispose();
    }

    private async Task Process(KeyboardEventArgs eventArgs)
    {
        if (eventArgs != null && eventArgs.Key != "Enter")
        {
            return;
        }
        _processing = true;
        try
        {
            StateHasChanged();
            if (string.IsNullOrWhiteSpace(_server))
            {
                snackbar.Add("请选择服务器", Severity.Error);
                return;
            }
            if (string.IsNullOrWhiteSpace(_commandText))
            {
                snackbar.Add("请输入需要执行的命令", Severity.Error);
                return;
            }

            if (sshConnectionPool == null)
            {
                sshConnectionPool = new SshConnectionPool("192.198.0.202", "root", "Sfqd@2025@06B");
            }

            var sshCommand = $"sshpass -p 'Sfqd@2025@06B' " +
                          $"ssh -o StrictHostKeyChecking=no " +
                          $"root@{_server} " +
                          $"'{_commandText}'";

            // var config = new ImprovedJumpHostConnectionManager.ConnectionConfig
            // {
            //     JumpHost = "192.198.0.202",
            //     JumpUser = "root",
            //     JumpPassword = "Sfqd@2025@06B",
            //     TargetHost = _server,
            //     TargetUser = "root",
            //     TargetPassword = "Sfqd@2025@06B"
            // };

            // var client = await connectionManager.GetTargetConnectionAsync(config);

            // 执行命令

            var result = sshConnectionPool.ExecuteCommand(sshCommand);
            _results = result.Split("\n").ToList();
            _historyCommandTexts.Add(_commandText);
            _commandText = string.Empty;
        }
        catch (Exception ex)
        {
            snackbar.Add($"处理过程中发生错误: {ex.Message}", Severity.Error);
        }
        finally
        {
            _processing = false;
        }
    }

    private void ClearResult()
    {
        _results.Clear();
    }

    private void ClearHistories()
    {
        _historyCommandTexts.Clear();
    }
}
